import {
    getEmployeeInfo,
    getEmployeeInfoByName,
    getEmployeeInfoByEmployeeNo,
    deleteEmployee,
    updateEmployeeInfo
} from '@/api/employeeApi';
import { getDepartmentById } from "@/api/departmentApi";

export default {
    props: ['employeeId'], // 通过 props 接收 employeeId 参数
    data() {
        return {
            showPassword: false,
            search: { account: '0' },
            employees: [],
            pages: [],
            page: {
                isEditing: false
            }, // 员工信息
            departmentCache: {}, // 部门缓存
            udpateEmployee: {},
            originalData: null // 保存原始数据，用于取消编辑时恢复
        };
    },
    computed: {
        currentDepartmentName() {
            if (!this.page.departmentId) return '未知';
            return this.departmentCache[this.page.departmentId] || '加载中...';
        }
    },
    methods: {
        UpdateEmployee(employee) {
            this.$set(employee, 'isEditing', !employee.isEditing);
            this.saveEmployeeChanges(employee);
        },
        async saveEmployeeChanges(employee) {
            try {
                // 这里应该调用更新员工信息的 API
                this.updateEmployee = {};
                this.updateEmployee.employeeId = employee.employeeId;
                this.updateEmployee.employeeNo = employee.employeeNo;
                this.updateEmployee.employeeName = employee.employeeName;
                this.updateEmployee.employeePhone = employee.employeePhone;
                this.updateEmployee.email = employee.email;
                this.updateEmployee.departmentId = employee.departmentId;
                this.updateEmployee.gender = employee.gender;
                this.updateEmployee.account = employee.account;
                this.updateEmployee.password = employee.password;
                this.updateEmployee.role = employee.role;
                this.updateEmployee.position = employee.position;
                this.updateEmployee.hireDate = employee.hireDate;
                this.updateEmployee.birthDate = employee.birthDate;
                this.updateEmployee.isActive = employee.isActive;
                this.updateEmployee.currentSalaryLevel = employee.currentSalaryLevel;
                this.updateEmployee.remainingAnnualLeave = employee.remainingAnnualLeave;
                this.updateEmployee.comments = employee.comments;
                const empResult = await updateEmployeeInfo(this.updateEmployee);
                if (empResult.code === 200) {
                    this.updateEmployee = {};
                }
            } catch (error) {
                console.error('更新员工信息失败:', error);
                this.$alert('更新失败，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },
        toggleEdit(employee){
            this.$set(employee, 'isEditing', !employee.isEditing);
            this.originalData = JSON.parse(JSON.stringify(employee));
        },
        // 取消编辑，恢复原始数据
        cancelEdit(employee) {
            // 恢复原始数据
            Object.assign(employee, this.originalData);
            // 切换编辑状态
            this.$set(employee, 'isEditing', false);
        },
        // 查询
        loadEmployeeDataById() {
            this.loadDataById();
        },
        loadEmployeeDataByName() {
            this.loadDataByName();
        },
        loadEmployeeDataByEmployeeNo() {
            this.loadDataByEmployeeNo();
        },
        // 加载部门名称
        async loadDepartmentName(departmentId) {
            if (!departmentId || this.departmentCache[departmentId]) return;

            this.loadingDepartment = true;
            try {
                const result = await getDepartmentById(departmentId);
                if (result.code === 200 && result.data) {
                    return result.data.departmentName;
                } else {
                    return '未知';
                }
            } catch (error) {
                console.error('获取部门信息失败:', error);
                this.$set(this.departmentCache, departmentId, '加载失败');
            }
        },

        // 加载数据
        async loadDataById() {
            try {
                // 1. 清空员工数组信息
                this.pages = [];
                // 2. 调用 API 获取员工信息
                const empResult = await getEmployeeInfo(this.search.account);
                if (empResult.code === 200) {
                    this.page = empResult.data;
                    this.$set(this.page, 'isEditing', false);
                    // 3. 加载部门名称
                    if (this.page.departmentId) {
                        const departmentName = await this.loadDepartmentName(this.page.departmentId);
                        this.page.departmentName = departmentName;
                    }
                    if (!this.pages.some(page => page.employeeId === this.page.employeeId)) {
                        this.pages.push(this.page);
                    }
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        async loadDataByName() {
            try {
                // 1. 清空员工数组信息
                this.pages = [];
                // 2. 调用 API 获取员工信息
                const empResult = await getEmployeeInfoByName(this.search.name);
                if (empResult.code === 200) {
                    this.employees = empResult.data;

                    // 3. 遍历 pages 数组，为每个员工加载部门名称
                    for (const employee of this.employees) {
                        if (employee.departmentId) {
                            const departmentName = await this.loadDepartmentName(employee.departmentId);
                            // 为当前员工对象添加 departmentName 属性
                            employee.departmentName = departmentName;
                            this.$set(employee, 'isEditing', false);
                        }
                    }
                    this.pages = this.employees;
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        async loadDataByEmployeeNo() {
            try {
                // 1. 清空员工数组信息
                this.pages = [];
                // 2. 调用 API 获取员工信息
                const empResult = await getEmployeeInfoByEmployeeNo(this.search.employeeNo);
                if (empResult.code === 200) {
                    this.page = empResult.data;
                    this.$set(this.page, 'isEditing', false);
                    // 3. 加载部门名称
                    if (this.page.departmentId) {
                        const departmentName = await this.loadDepartmentName(this.page.departmentId);
                        this.page.departmentName = departmentName;
                    }
                    if (!this.pages.some(page => page.employeeId === this.page.employeeId)) {
                        this.pages.push(this.page);
                    }
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        // 其他格式化方法保持不变...
        formatDate(date) {
            if (!date) return '未知';
            const d = new Date(date);
            return d.toLocaleDateString('zh-CN');
        },

        formatRole(role) {
            const roles = {
                0: '普通员工',
                1: '部门经理',
                2: '总经理'
            };
            return roles[role] || '未知';
        },

        formatGender(gender) {
            const genders = {
                0: '男',
                1: '女',
                2: '未知'
            };
            return genders[gender] || '未知';
        },

        formatActiveStatus(isActive) {
            return isActive ? '在职' : '离职';
        },

        formatSalaryLevel(level) {
            return level ? `级别 ${level}` : '未设置';
        },

        formatAnnualLeave(days) {
            return days !== null && days !== undefined ? `${days} 天` : '未设置';
        },
        async deleteEmployee(employeeId) {
            try {
                // 弹出确认对话框
                await this.$confirm('确定要删除该员工吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                // 如果用户点击确定，则执行删除操作
                const result = await deleteEmployee(employeeId);
                if (result.code === 200) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    // 删除成功后，从页面数据中移除该员工
                    const index = this.pages.findIndex(emp => emp.employeeId === employeeId);
                    if (index !== -1) {
                        this.pages.splice(index, 1);
                    }
                } else {
                    this.$message({
                        message: '删除失败',
                        type: 'error'
                    });
                }
            } catch (error) {
                // 如果用户点击取消，或者发生其他错误，则捕获异常
                if (error !== 'cancel') {
                    console.error('删除失败:', error);
                    this.$alert('网络错误，请稍后再试', '提示', {
                        confirmButtonText: '确定'
                    });
                }
            }
        },
        goBack() {
            this.$router.replace({ path: '/employee/AllEmployee' });
        }
    },
    mounted() {
        // 检查是否有 employeeId 参数
        if (this.employeeId) {
            this.search.account = this.employeeId;
            this.loadDataById();
        }
    },

};